/*
 * Copyright (c) 2007-2008, Thomas Krause (tho.krause@gmail.com)
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *     * Neither the name of gidoo nor the names of its contributors may be used to
 *       endorse or promote products derived from this software without specific
 *       prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.gidoo.cms.admin.addins;

import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.Model;
import org.gidoo.cms.GidooCMS;
import org.gidoo.cms.admin.AdminPage;
import org.gidoo.cms.data.CMSSection;
import org.gidoo.cms.data.RegisteredUser;
import org.gidoo.cms.dbconnection.DatabaseConnectionException;
import org.gidoo.cms.dbconnection.Persistance;

/**
 * A panel where you can adminstrate a single section.
 * @author Thomas
 */
public class SingleSectionPanel extends AddInPanel
{
    
  private Form formDelete;
  private Button btDelete;
  
  private Form formOrder;
  
  private Form formChange;
  private TextField txtURL;
  private TextField txtName;
  
  private CMSSection theSection;
  private AdminPage theParent;
  
  /**
   * Creates a new instance of UsersPanel
   * @param id The wicket id.
   * @param section The url of the section.
   */
  public SingleSectionPanel(String id, CMSSection section, AdminPage parent)
  {
    super(id);
    
    formChange = new Form("formChange");
    
    txtURL = new TextField("txtURL", new Model(""));
    txtName = new TextField("txtName", new Model(""));
    
    formChange.add(new Button("btChange", new Model(getString("change")))
    {
      @Override
      public void onSubmit()
      {
        try
        {
          CMSSection tmp = ((GidooCMS) getApplication()).getDb().getSectionByExactUrl(txtURL.getModelObjectAsString());
          if(tmp == null || theSection.equals(tmp))
          {
            theSection.setName(txtName.getModelObjectAsString());
            theSection.setUrl(txtURL.getModelObjectAsString());
            theSection = (CMSSection) ((GidooCMS) getApplication()).getDb().merge(theSection);
          }
          else
          {
            error(getString("alreadyexists"));
          }
          updateDataAndView(theSection, theParent);
        }
        catch (DatabaseConnectionException ex)
        {
          Logger.getLogger(SingleSectionPanel.class.getName()).log(Level.SEVERE, null, ex);
          error(getString("dberror"));
        }
      }      
    });
    
    formChange.add(txtName);
    formChange.add(txtURL);
    add(formChange);
    
    updateDataAndView(section, parent);
    
    formDelete = new Form("formDelete");
    btDelete = new Button("btDelete", new Model(getString("deleteSection")))
    {
      
      @Override
      public void onSubmit()
      {
        try
        {           
          
          List<RegisteredUser> users = ((GidooCMS) getApplication()).getDb().getAllUsers();
          
          for(RegisteredUser u : users)
          {
            if(u.getSections_publish().remove(theSection) ||
               u.getSections_edit().remove(theSection))
            {
              u = (RegisteredUser) ((GidooCMS) getApplication()).getDb().merge(u);
            }
          }
          
          ((GidooCMS) getApplication()).getDb().remove(theSection);
          ((GidooCMS) getApplication()).getDb().mergeListOfSections(((GidooCMS) getApplication()).getDb().getAllSections());
          theParent.setSelectedNode(null);
          theParent.updateDataAndView();
        }
        catch(DatabaseConnectionException ex)
        {
          Logger.getLogger(SingleSectionPanel.class.getName()).log(Level.SEVERE, null, ex);
          error(ex.getMessage());
        }
      }
      
    };
    
    formDelete.add(btDelete);
    add(formDelete);
    
    formOrder = new Form("formOrder");
    
    AjaxButton btUp = new AjaxButton("btUp") 
    {

      @Override
      protected void onSubmit(AjaxRequestTarget target, Form form)
      {
        sectionUp();
        target.addComponent(theParent.getTreeNav());
        target.addComponent(feedback);
      }
    };
    btUp.setModel(new Model(getString("up")));
    
    formOrder.add(btUp);
    
    AjaxButton btDown = new AjaxButton("btDown") {

      @Override
      protected void onSubmit(AjaxRequestTarget target, Form form)
      {
        sectionDown();
        target.addComponent(theParent.getTreeNav());
        target.addComponent(feedback);
      }
    };
    btDown.setModel(new Model(getString("down")));
    
    formOrder.add(btDown);
    
    add(formOrder);
    
    
  }
  
  private void sectionUp()
  {
    if(theSection == null)
      return;
    
    try
    {
      List<CMSSection> siblings = new LinkedList<CMSSection>(((GidooCMS) getApplication()).getDb().getAllSections());
      int oldPosition = theSection.getPosition();
        
      if(oldPosition > 0 && oldPosition < siblings.size())
      {
        CMSSection tmp = siblings.get(oldPosition-1);
        siblings.set(oldPosition-1, theSection);
        siblings.set(oldPosition, tmp);
        siblings = ((GidooCMS) getApplication()).getDb().mergeListOfSections(siblings);
        theSection = siblings.get(oldPosition-1);
      }
      
      theParent.updateTreeModel(null, theSection);
      
    }
    catch (DatabaseConnectionException ex)
    {
      Logger.getLogger(SingleSectionPanel.class.getName()).log(Level.SEVERE, null, ex);
      error(getString("dberror"));
    }
    
  }
  
  private void sectionDown()
  {
    if(theSection == null)
      return;
    
    try
    {
      List<CMSSection> siblings = new LinkedList<CMSSection>(((GidooCMS) getApplication()).getDb().getAllSections());
      int oldPosition = theSection.getPosition();
        
      if(oldPosition >= 0 && oldPosition < siblings.size()-1)
      {
        CMSSection tmp = siblings.get(oldPosition+1);
        siblings.set(oldPosition+1, theSection);
        siblings.set(oldPosition, tmp);
        siblings = ((GidooCMS) getApplication()).getDb().mergeListOfSections(siblings);
        theSection = siblings.get(oldPosition+1);
      }
      
      theParent.updateTreeModel(null, theSection);
      
    }
    catch (DatabaseConnectionException ex)
    {
      Logger.getLogger(SingleSectionPanel.class.getName()).log(Level.SEVERE, null, ex);
      error(getString("dberror"));
    }
    
  }
  
  public void updateDataAndView(CMSSection section, AdminPage parent)
  {
    this.theSection = section;
    this.theParent = parent;
    
    lblTitle.setModelObject(getString("title") + theSection.getName());
    
    txtName.setModelObject(theSection.getName());
    txtURL.setModelObject(theSection.getUrl());
    
  }
  
}
